using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.UI;

public class FoodMenuItem : MonoBehaviour
{
    public Text tesla1;
    public Text tesla2;
    public Text price;
    public Image iconType;
    public Image[] starLevel;
    private int foodType;
    public GameObject hideObj1;
    public GameObject hideObj2;

    void Start()
    {
        GlobalEventManager.OnEvent<int>("FoodTypeUpgradeEvent", OnFoodTypeUpgradeEvent);
    }

    void OnDestroy()
    {
        GlobalEventManager.OffEvent<int>("FoodTypeUpgradeEvent", OnFoodTypeUpgradeEvent);
    }

    private void OnFoodTypeUpgradeEvent(int type)
    {
        if (type == foodType)
        {
            initData(type);
        }
    }

    public void OnBuyClick()
    {
        float tesla = UserManager.Instance.GetUserInfo()["Tesla"].ToObject<float>();
        float pv = float.Parse(price.text);
        if (tesla < pv)
        {
            Tools.ShowTipToast("Not enough stars");
            return;
        }

        UserManager.Instance.SubtractTesla(pv);
        FoodScoreManager.Instance.ScoreUp(foodType);
        Tools.ShowTipToast("Upgrade Successfully");
    }

    public void initData(int type)
    {
        foodType = type;
        Sprite[] sprites = ResManager.Instance.GetGoodsIcons();
        iconType.sprite = sprites[type];
        int lv = FoodScoreManager.Instance.GetScoreByType(type);

        UpdateStarLevel(lv);
        UpdateInfos(type);

    }

    public void UpdateStarLevel(int lv)
    {
        for (int i = 0; i < starLevel.Length; i++)
        {
            if (i < lv)
            {
                starLevel[i].gameObject.SetActive(true);
            }
            else
            {
                starLevel[i].gameObject.SetActive(false);
            }
        }
    }

    public void UpdateInfos(int type)
    {
        int lv = FoodScoreManager.Instance.GetScoreByType(type);
        JArray r = (JArray)Data.foodMenuCfg[type]["reward"];
        JArray u = (JArray)Data.foodMenuCfg[type]["upgrade_cost"];


        if (lv > u.Count)
        {
            price.transform.parent.transform.GetComponent<Button>().interactable = false;
        }
        else
        {
            price.text = u[lv - 1].ToString();

        }

        if (lv < r.Count)
        {
            tesla1.text = r[lv - 1].ToString();
            tesla2.text = r[lv].ToString();
        }
        else
        {
            hideObj1.SetActive(false);
            hideObj2.SetActive(false);
        }
    }
}
